import { signal, computed } from "@preact/signals";
import { toast as toast_ } from "./Vendor";
import { boxFilter } from "./suggest";

export const hasIme = signal(false);
export const isPortrait = signal(false);
export const findFavo = signal(false);
export const isSearchFocus = signal(false);
export const slideMoving = signal(false);
export const slideTouching = signal(false);
export const slideTuning = computed(
  () => slideMoving.value && slideTouching.value,
);
export const logo = signal("");
export const toastText = signal("");

export const boxes = signal([]);
export const wordSignal = signal("");
export const filteredBox = computed(() =>
  boxFilter(
    boxes.value,
    "title",
    findFavo.value ? wordSignal.value : "",
    false,
  ),
);

export const toast = (() => {
  let id = -1;

  return (text) => {
    if (toast_) {
      toast_(text);
    } else {
      if (id) clearTimeout(id);
      toastText.value = text;
      id = setTimeout(() => {
        toastText.value = "";
      }, 1200);
    }
  };
})();

function debounce(call, delay) {
  let id = -1;
  return (...p) => {
    if (id !== -1) clearTimeout(id);
    id = setTimeout(() => {
      call(...p);
      id = -1;
    }, delay);
  };
}

export const setWord = debounce((v) => {
  wordSignal.value = v;
}, 100);

let currentHeight = window.innerHeight;

function checkPortrait() {
  return window.innerWidth < window.innerHeight * 1.25;
}

isPortrait.value = checkPortrait();

window.addEventListener(
  "resize",
  debounce(() => {
    if (checkPortrait() === isPortrait.value) {
      const delta = Math.abs(window.innerHeight - currentHeight);
      if (delta > 150) {
        hasIme.value = window.innerHeight < currentHeight;
        currentHeight = window.innerHeight;
      }
    } else {
      isPortrait.value = checkPortrait();
      currentHeight = window.innerHeight;
    }
  }),
);
